/*
 * xmega_timer.c
 *
 *  Created on: 2011/05/08
 *      Author: AKS
 */
#include "core/include/aks_processor.h"
#include "core/include/types.h"

#include "chip/include/chip.h"

/* -------- System Tick Counter --------- */
static WORD systemTick = 0;
void systemFreeRunTimer(void)
{
    systemTick++;

    return;
}

WORD TIMER_systemTick(void)
{
    return systemTick;
}


TIMER_CALLBACK timerCallbackTable[TIMER_NUM]
=
{
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    systemFreeRunTimer,
    NULL
};

BOOL Init_Timer(BYTE tick_ms)
{
	/* initialize registers */
	TCC0.CTRLA = TC_CLKSEL_DIV256_gc;
	TCC0.CTRLB = TC_WGMODE_NORMAL_gc;
	TCC0.CTRLC = 0;
	TCC0.CTRLD = TC_EVACT_OFF_gc | TC_EVSEL_OFF_gc;
	TCC0.CTRLE = 0;

	/* intrrupt Enable Reg. */
	TCC0.INTCTRLA = TC_ERRINTLVL_OFF_gc | TC_OVFINTLVL_HI_gc;
	TCC0.INTCTRLB = TC_CCDINTLVL_OFF_gc | TC_CCCINTLVL_OFF_gc | TC_CCBINTLVL_OFF_gc | TC_CCAINTLVL_OFF_gc;
	TCC0.INTFLAGS = 1; // enable ovfif

	/* set freq. */
	/* tick[ms] */
	/* sysclk = 32MHz, DIV = 256, T = 1/125[ms] */
	TCC0.PER = 125L * tick_ms;

    return TRUE;
}

BOOL TIMER_resetCallback(TIMER_ID id, TIMER_CALLBACK count)
{
	if(id < TIMER_NUM)
	{
		timerCallbackTable[id] = count;

		return TRUE;
	}
	else
    {
        return FALSE;
    }
}


ISR(TCC0_OVF_vect)
{
Disable_Int();
xmega_mem_enter_ISR();

	int i;
	for(i=TIMER_0 ; i<TIMER_NUM ; ++i )
	{
        if(timerCallbackTable[i]!=NULL)
        {
            timerCallbackTable[i]();
        }
    }

xmega_mem_exit_ISR();
Enable_Int();
	return;
}
